<?php
namespace PsiFramework\Applications\AlloMediaUser\Classes\Actions;

import("Applications.AlloMediaPortal.Classes.Actions.AlloMediaUserAction");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");
import("Plugins.Shop.Classes.Model.Order");

use \PsiFramework\Applications\AlloMediaPortal\Classes\Actions\AlloMediaUserAction;
use \PsiFramework\Classes\Util\HTTP\AuthenticationManager;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Plugins\Shop\Classes\Model\Order;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
class ValidateBasketAction extends AlloMediaUserAction
{

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     */
    public function execute()
    {
        parent::execute();
        
        $orderDao = DAOFactory::getDAO('Order');
        $order = $orderDao->retrieveActiveOrderByUser($this->_user, false);
        
        $responseIds = $this->_request->getParameter('responseId');
        $quantities = $this->_request->getParameter('quantity');
        
        if (!isNullOrEmptyString($responseIds) && !isNullOrEmptyString($quantities)) {
            $linkDao = DAOFactory::getDAO('OrderItemLink');
            $links = $order->getItems();
            foreach ($links as $link) {
                for ($i=0; $i<count($links); $i++) {
                    $responseId = $responseIds[$i];
                    $quantity = $quantities [$i];
                    
                    if ($responseId == $link->getItem()->getItem()->getValue()) {
                        $link->setQuantity($quantity);
                        $linkDao->save($link);
                        break;
                    }
                }
            }
        }
        
        $submit = $this->_request->getParameter('submitType');
        if (isNullOrEmptyString($submit)) {
            $submit = 'UPDATE';
        } else {
            $submit = 'CHECKOUT';
        }
        
        $this->findForward($submit);
    }
}
